# _*_coding:utf-8_*_
"""
   ATS 1.0(Automated Test Server, Version 1.0) SubSite Plan File Parser,
   Developed by Ivy.Li 2013.03.18.
   (C)Copyright 2013 Hech. All rights reserved
"""
import configparser as ConfigParser
import os

# error messages define
NO_DEVS = 31
INVAL_DEVS = 32
NO_TESTS = 33
INVAL_TESTS = 34
NO_TESTSInDev = 35
INVAL_TESTSInDev = 36
NO_SSPF_FOUND = 37
# INVAL_SSITES_SEQ=8
INVAL_TESTS_OUTPUTS = 1007
INVAL_REPEATS = 1011


class SSPF:
    """
    header: {
    'Name': 'ATS Project Plan  File',
    'Version':'1.0',
    'TYP':'Ivy',
    'Create Date':'14/03/2013'
    }

    subsites:
    {

        "subsite_name":
            {
            'parallel':True or False
            'uaps':{}
            'tests':[]
            'devs':[]
            }
        ...
    }
    devs:{
       "dev_name":
        {
        'tests':[],
        'uaps':{}
        }
        ...
    }

    tests:
        {
        'test_name':[outputs list]
        }

    repeat:{
        'SS1':100,
        'Dev2':10,
        'LoopUnitName': LoopNum
        }
    ssites:[subsite execution sequence]
    """

    def __init__(self, sspf=None):
        if sspf:
            self.load(sspf)
        else:
            self.clear()

    def clear(self):
        self.header = {}
        self.subsites = {}
        self.ssites = []
        self.devs = {}
        self.tests = {}
        self.repeat = {}
        self.error = 0

    def set_ssites(self, ssites):
        self.ssites = ssites

    def load(self, sspf):
        global nos, items
        if not os.path.exists(sspf):
            self.error = NO_SSPF_FOUND
            return

        self.clear()

        cp = ConfigParser.ConfigParser()
        cp.read(sspf)

        # get header
        keys = ['Name', 'Version', 'TYP', 'Create Date']
        for k in keys:
            self.header[k] = cp.get('Header', k)

        # get subsites
        for sec in cp.sections():
            if sec.startswith('Subsite'):
                ssite_name = sec.split()[1]
                self.ssites.append(ssite_name)
                temp_d = {}
                self.subsites[ssite_name] = temp_d
                try:
                    tmp_v = cp.get(sec, 'Devs')
                    if tmp_v:
                        temp_d['devs'] = tmp_v.split(',')
                    else:
                        temp_d['devs'] = []
                except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
                    self.error = NO_DEVS
                    return
                except:
                    self.error = INVAL_DEVS
                    return

                try:
                    tem = cp.get(sec, 'Parallel')
                    if tem.lower() == 'true':
                        temp_d['parallel'] = True
                    else:
                        temp_d['parallel'] = False
                except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
                    temp_d['parallel'] = False
                    return

                try:
                    tmp_v = cp.get(sec, 'Tests')
                    if tmp_v:
                        temp_d['tests'] = tmp_v.split(',')
                    else:
                        temp_d['tests'] = []
                except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
                    self.error = NO_TESTS
                    return
                except:
                    self.error = INVAL_TESTS
                    return

                temp_d['uaps'] = {}
                try:
                    uap = cp.get(sec, 'UAP_SUBSITE_BEGIN')
                    if uap:
                        temp_d['uaps']['UAP_SUBSITE_BEGIN'] = uap
                except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
                    pass

                try:
                    uap = cp.get(sec, 'UAP_SUBSITE_END')
                    if uap:
                        temp_d['uaps']['UAP_SUBSITE_END'] = uap
                except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
                    pass

                try:
                    uap = cp.get(sec, 'UAP_DEVICE_BEGIN')
                    if uap:
                        temp_d['uaps']['UAP_DEVICE_BEGIN'] = uap
                except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
                    pass

                try:
                    uap = cp.get(sec, 'UAP_DEVICE_END')
                    if uap:
                        temp_d['uaps']['UAP_DEVICE_END'] = uap
                except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
                    pass

                try:
                    uap = cp.get(sec, 'UAP_TEST_BEGIN')
                    if uap:
                        temp_d['uaps']['UAP_TEST_BEGIN'] = uap
                except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
                    pass

                try:
                    uap = cp.get(sec, 'UAP_TEST_END')
                    if uap:
                        temp_d['uaps']['UAP_TEST_END'] = uap
                except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
                    pass

            elif sec.startswith('Device'):
                dev_name = sec.split()[1]
                temp_d = {}
                self.devs[dev_name] = temp_d

                try:
                    tmp_v = cp.get(sec, 'Tests')
                    if tmp_v:
                        temp_d['tests'] = tmp_v.split(',')
                    else:
                        temp_d['tests'] = []
                except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
                    self.error = NO_TESTSInDev
                    return
                except:
                    self.error = INVAL_TESTSInDev
                    return

                temp_d['uaps'] = {}
                try:
                    uap = cp.get(sec, 'UAP_DEVICE_BEGIN')
                    if uap:
                        temp_d['uaps']['UAP_DEVICE_BEGIN'] = uap
                except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
                    pass

                try:
                    uap = cp.get(sec, 'UAP_DEVICE_END')
                    if uap:
                        temp_d['uaps']['UAP_DEVICE_END'] = uap
                except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
                    pass

                try:
                    uap = cp.get(sec, 'UAP_TEST_BEGIN')
                    if uap:
                        temp_d['uaps']['UAP_TEST_BEGIN'] = uap
                except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
                    pass

                try:
                    uap = cp.get(sec, 'UAP_TEST_END')
                    if uap:
                        temp_d['uaps']['UAP_TEST_END'] = uap
                except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
                    pass
            elif sec == 'Tests':
                for k, v in cp.items('Tests'):
                    try:
                        v = v.split(',')
                        if v and not (len(v) == 1 and v[0] == ''):
                            self.tests[k] = v
                    except:
                        self.error = INVAL_TESTS_OUTPUTS
                        continue
            elif sec == 'Repeat':
                try:
                    tmp_v = cp.get('Repeat', 'RepeatName')
                    if tmp_v:
                        items = tmp_v.split(',')
                    tmp_v = cp.get('Repeat', 'RepeatNumber')
                    if tmp_v:
                        nos = tmp_v.split(',')
                    for i in range(len(items)):
                        self.repeat[items[i]] = int(nos[i])
                except:
                    self.error = INVAL_REPEATS
#            elif sec=='Ssites_seq':
#                try:
#                    self.ssites=eval(cp.get('Ssites_seq','Ssites_seq'))
#                except:
#                    self.error=INVAL_SSITES_SEQ

# Test code
# sspf=SSPF(r'D:\Eclipse_Home\MRBIG_Cust\plans\sspf\ATS_SingleTestPlan3.sspf')
# print sspf.header
# print sspf.error,'===========error'
# print sspf.ssites,'=====ssites'
# for key in sspf.subsites:
#    print key,'<-----ss---->',sspf.subsites[key]
# for key in sspf.devs:
#    print key,'<--------->',sspf.devs[key]
# for key in sspf.tests:
#    print key,'<--------->',sspf.tests[key]
# print sspf.repeat
